/**
* Purpose:Updated the Trigger to  Include 4 New Fields required for Reporting Purpose
* IDC Accenture for NMR    v2.1    26th Apr 2012        
* Bhumika Udani            v2.1    24th May 2012        updates as per AD-29831, disallowing GSM DSM to accept leads 
*
**/     

trigger UpdatePrimaryOwner on Lead (before insert,before Update) {
      
      // Declaring collections to be used        
      List<id> LeadOwnerIds = new List<id>();
      List<Lead> NewLeads = new List<Lead>();
      List<Lead> NewLeadsQueue = new List<Lead>();

      Map<id,Lead> LeadOwnerIdsQueue = new Map<id,Lead>();
      Map<id,User> OwnerMap = new Map<id,User>();
      Map<id,String> OwnerMapQueue = new Map<id,String>();
      
      //Fetching recordtype Id for OOR and NMR to segregate logic updates
      ID localAdvertiserRecordTypeID = RecordTypeHelper.GetRecordTypeID('Lead', 'Local Advertiser');
      ID NMRRecordTypeID = RecordTypeHelper.GetRecordTypeID('Lead', 'NMR Lead');
      ID NMRRecordTypeCustId = RecordTypeHelper.GetRecordTypeID('Lead','NMR Lead with CustomerId');
      
      
      profile gsmProfileID = [select id from profile where name  =: OORTextConstant.GSM_DSM_PROFILE_NAME];      
      system.debug('Thats GSM Id --> '+gsmProfileID);

      for(lead ld :Trigger.new){
      
          String OwnerCheck=ld.OwnerId;
            if(ld.RecordTypeId == localAdvertiserRecordTypeID){
                   if(OwnerCheck.startsWith(OORTextConstant.QUEUE_OWNER)){
                           LeadOwnerIdsQueue.put(ld.ownerid,ld);
                           NewLeadsQueue.add(ld);
                    }
                   else{
                        //If owner is updated for JIRA AD-29831
                        
                        if(Trigger.IsUpdate && ld.OwnerId!=Trigger.Oldmap.get(ld.Id).OwnerID){
                        
                        // Owner is changed to User
                              if(OwnerCheck.startsWith(OORTextConstant.USER_OWNER)){
                                  
                                system.debug(gsmProfileID.id +' GSM user profile Id: '+userinfo.getProfileId());

                        // Owner of the lead is GSM DSM user, do not allow owner update        
                                if(userinfo.getProfileId() == gsmProfileID.id ){
                                     ld.addError(OORTextConstant.GSM_DSM_CANNOT_ACCEPT_LEAD);
                                 }
                            }
                        }
                        else{
                            LeadOwnerIds.add(ld.ownerid);
                            NewLeads.add(ld); 
                        }
                    }
            }

        //NMR Lead ATTUID Update
            else if(ld.RecordTypeId == NMRRecordTypeID || ld.RecordTypeId == NMRRecordTypeCustId){
                        LeadOwnerIds.add(ld.NMR_Sales_Rep__c);
                        LeadOwnerIds.add(ld.ownerId);
                        NewLeads.add(ld);
                }
      }
      
      if(LeadOwnerIds.size()>0){          
          List<User> LeadOwners = [select id,Name,ATTUID__c,AFrontier_Employee_ID__c,SFA_Office__c,SFA_Office_Name__c,ManagerId from user where id in :LeadOwnerIds];
         
          for(User U : LeadOwners){
                 OwnerMap.put(U.Id,U);
             }
      
          for(lead Nlead : NewLeads){
               
               // If Local Advertiser Lead
               if(Nlead.RecordtypeId == localAdvertiserRecordTypeID){

                    // below line updates the Last worked in case of owner change
                    if(Trigger.IsUpdate && Nlead.OwnerId!=Trigger.Oldmap.get(Nlead.Id).OwnerID){
                        Nlead.Last_Worked__c=DateTime.NOW();
                      } 
                        Nlead.Primary_Owner__C = OwnerMap.get(Nlead.ownerid).Name; 
                        Nlead.Primary_Owner_ATTUID__c=OwnerMap.get(Nlead.ownerid).ATTUID__c;
                        Nlead.User_Manager__c=OwnerMap.get(Nlead.ownerid).ManagerId;
                        Nlead.User_Office_Code__c=OwnerMap.get(Nlead.ownerid).SFA_Office__c;
                        Nlead.User_Office_Name__c=OwnerMap.get(Nlead.ownerid).SFA_Office_Name__c;
                        Nlead.Primary_Owner_AFrontier_Employee_ID__c=OwnerMap.get(Nlead.ownerid).AFrontier_Employee_ID__c;

                // populate on insert or update the Date Assigned in case of owner change
                if(Trigger.Isinsert || Nlead.OwnerId!=Trigger.Oldmap.get(Nlead.Id).OwnerID ){
                        Nlead.Date_Assigned__c=Date.Today();  
                    }
              } //Local Advertiser condition check ends
            
            //Condition for NMR
            
            else If(Nlead.RecordtypeId == NMRRecordTypeID || Nlead.RecordTypeId == NMRRecordTypeCustId){
                        if(OwnerMap.containskey(Nlead.NMR_Sales_Rep__c)){
                            if(OwnerMap.get(Nlead.NMR_Sales_Rep__c).ATTUID__c != NULL){
                                Nlead.ATTUID__c=OwnerMap.get(Nlead.NMR_Sales_Rep__c).ATTUID__c;
                            }
                        } 
                        else if (OwnerMap.containskey(Nlead.ownerId)){
                                if(OwnerMap.get(Nlead.ownerId).ATTUID__c != NULL){
                                    Nlead.ATTUID__c=OwnerMap.get(Nlead.ownerId).ATTUID__c;
                                }
                        }
                        if(Trigger.IsUpdate && Nlead.OwnerId!=Trigger.Oldmap.get(Nlead.Id).OwnerID){
                                Nlead.Last_Worked__c=DateTime.NOW();
                        }
                        if(Trigger.Isinsert || Nlead.OwnerId!=Trigger.Oldmap.get(Nlead.Id).OwnerID ){
                                Nlead.Date_Assigned__c=Date.Today();  
                        }
            } // NMR Condition check ends
         }
      }
      
    
    if(LeadOwnerIdsQueue.size()>0){          
          //List<User> LeadOwners = [select id,Name,ATTUID__c,AFrontier_Employee_ID__c,SFA_Office__c,SFA_Office_Name__c,ManagerId from user where id in :LeadOwnerIds];
         
            for(QueueSobject q : [Select Id, q.Queue.Name,q.Queue.ID from QueueSobject q 
                            where q.SobjectType = 'Lead']){
            
                   if(LeadOwnerIdsQueue.containsKey(q.Queue.Id)){
                         OwnerMapQueue.put(q.Queue.ID,q.Queue.Name);
                   }
            }
      
      for(lead Nlead : NewLeadsQueue){
               
            Nlead.Primary_Owner__C = OwnerMapQueue.get(Nlead.ownerid);
            
            String myString1 = OwnerMapQueue.get(Nlead.ownerid);
            integer firstindex = myString1.indexOf('(') + 1;
            String OfficeCode = '';
            
            if(firstindex > 0){
                OfficeCode = myString1.Substring(firstindex,firstindex+3); 
            }
            else{
                firstindex = myString1.indexOf('[') + 1;
                OfficeCode = myString1.Substring(firstindex,firstindex+3);
            }
            
            Nlead.Primary_Owner_ATTUID__c='';
            Nlead.User_Manager__c=NULL;
            Nlead.User_Office_Code__c = OfficeCode;
            Nlead.User_Office_Name__c='';
            Nlead.Primary_Owner_AFrontier_Employee_ID__c='';
            
           }
    }
}